// SmartInput Chrome扩展弹出窗口脚本
class SmartInputPopup {
  constructor() {
    this.isConnected = false;
    this.deviceId = null;
    this.userId = null;
    this.statusInterval = null;
    
    this.init();
  }
  
  async init() {
    console.log('SmartInput弹出窗口初始化...');
    
    // 获取DOM元素
    this.getElements();
    
    // 设置事件监听器
    this.setupEventListeners();
    
    // 添加测试按钮事件
    if (this.testBtn) {
      this.testBtn.addEventListener('click', () => {
        this.syncCurrentText();
      });
    }
    
    // 添加刷新状态按钮事件
    if (this.refreshStatusBtn) {
      this.refreshStatusBtn.addEventListener('click', async () => {
        console.log('手动刷新连接状态并尝试重新连接');
        await this.refreshAndReconnect();
      });
    }
    
    // 加载状态
    await this.loadStatus();
    
    // 检查登录状态并更新界面
    await this.checkLoginStatus();
    
    // 更新UI
    await this.updateUI();
    // 启动连接状态轮询
    this.startStatusPolling();
    
    // 调试信息
    console.log('Popup初始化完成，最终状态:', {
      userId: this.userId,
      hasToken: !!this.token,
      userName: this.userName,
      isConnected: this.isConnected
    });
  }

  startStatusPolling() {
    if (this.statusInterval) clearInterval(this.statusInterval);
    
    // 立即检查一次状态
    this.checkConnectionStatus();
    
    // 每2秒检测一次（更频繁的检查）
    this.statusInterval = setInterval(async () => {
      await this.checkConnectionStatus();
    }, 2000);
  }
  
  async refreshAndReconnect() {
    try {
      console.log('开始刷新状态并尝试重新连接...');
      
      // 首先检查当前状态
      await this.checkConnectionStatus();
      
      // 如果没有连接，尝试重新连接
      if (!this.isConnected) {
        console.log('连接未建立，尝试重新连接...');
        this.showInfo('正在尝试重新连接...');
        
        // 发送重新连接请求到background
        const result = await chrome.runtime.sendMessage({ action: 'reconnect' });
        
        if (result && result.success) {
          this.showSuccess('重新连接成功');
          // 等待一下再检查状态
          setTimeout(async () => {
            await this.checkConnectionStatus();
          }, 1000);
        } else {
          this.showError('重新连接失败: ' + (result?.error || '未知错误'));
        }
      } else {
        this.showSuccess('连接状态良好');
      }
    } catch (error) {
      console.error('刷新和重连失败:', error);
      this.showError('操作失败: ' + error.message);
    }
  }

  async checkConnectionStatus() {
    try {
      const status = await chrome.runtime.sendMessage({ action: 'getStatus' });
      if (status && typeof status.isConnected === 'boolean') {
        const wasConnected = this.isConnected;
        this.isConnected = status.isConnected;
        
        // 记录详细的状态信息
        console.log('连接状态详情:', {
          isConnected: status.isConnected,
          websocketState: status.websocketState,
          deviceId: status.deviceId,
          hasToken: status.hasToken,
          lastHeartbeat: status.lastHeartbeat,
          reconnectAttempts: status.reconnectAttempts
        });
        
        // 如果连接状态发生变化，立即更新UI
        if (wasConnected !== this.isConnected) {
          console.log('连接状态变化:', wasConnected, '->', this.isConnected);
          this.updateConnectionStatus();
          
          // 显示状态变化通知
          if (this.isConnected) {
            this.showSuccess('WebSocket连接已建立');
          } else {
            this.showError('WebSocket连接已断开');
          }
        }
        
        // 如果设备ID有更新，也更新设备ID显示
        if (status.deviceId && status.deviceId !== this.deviceId) {
          this.deviceId = status.deviceId;
          await this.showDeviceId();
        }
        
        // 如果用户信息有更新，也更新用户信息显示
        if (status.userName !== this.userName) {
          this.userName = status.userName;
          this.updateUserInfo();
        }
        
        // 添加连接状态到活动列表
        if (status.isConnected) {
          this.addActivity('🔗', `连接状态: ${status.websocketState}`);
        } else {
          this.addActivity('❌', `连接断开: ${status.websocketState}`);
        }
      }
    } catch (e) {
      console.error('检查连接状态失败:', e);
      const wasConnected = this.isConnected;
      this.isConnected = false;
      
      if (wasConnected !== this.isConnected) {
        this.updateConnectionStatus();
        this.showError('无法获取连接状态');
      }
    }
  }
  
  getElements() {
    // 登录元素
    this.loginSection = document.getElementById('loginSection');
    this.userNameInput = document.getElementById('username');
    this.passwordInput = document.getElementById('password');
    this.loginBtn = document.getElementById('loginBtn');
    this.loginError = document.getElementById('loginError');
    this.mainContent = document.querySelector('.main-content');

    // 注册元素
    this.registerSection = document.getElementById('registerSection');
    this.regUserNameInput = document.getElementById('regUsername');
    this.regPasswordInput = document.getElementById('regPassword');
    this.regConfirmPasswordInput = document.getElementById('regConfirmPassword');
    this.registerBtn = document.getElementById('registerBtn');
    this.registerError = document.getElementById('registerError');
    this.showRegisterBtn = document.getElementById('showRegisterBtn');
    this.showLoginBtn = document.getElementById('showLoginBtn');

    // 状态指示器
    this.statusIndicator = document.getElementById('statusIndicator');
    this.statusDot = this.statusIndicator.querySelector('.status-dot');
    this.statusText = this.statusIndicator.querySelector('.status-text');
    
    // 状态显示元素
    this.connectionStatus = document.getElementById('connectionStatus');
    this.userStatus = document.getElementById('userStatus');
    
    // 快捷操作
    this.settingsBtn = document.getElementById('settingsBtn');
    this.helpBtn = document.getElementById('helpBtn');
    this.logoutBtn = document.getElementById('logoutBtn');
    this.testBtn = document.getElementById('testBtn');
    this.validateTokenBtn = document.getElementById('validateTokenBtn');
    this.refreshStatusBtn = document.getElementById('refreshStatusBtn');
    
    // 活动列表
    this.activityList = document.getElementById('activityList');
    
    // 设备信息
    this.deviceIdElement = document.getElementById('deviceId');
    
    // 用户信息
    this.userInfo = document.getElementById('userInfo');
    this.userNameElement = document.getElementById('userName');
    
    // 调试日志：检查关键元素是否正确获取
    console.log('DOM元素获取状态:', {
      loginSection: !!this.loginSection,
      registerSection: !!this.registerSection,
      mainContent: !!this.mainContent,
      userNameInput: !!this.userNameInput,
      passwordInput: !!this.passwordInput,
      loginBtn: !!this.loginBtn
    });
  }

  // 辅助函数：显示/隐藏元素
  showElement(element) {
    if (element) {
      element.classList.remove('hidden');
    }
  }

  hideElement(element) {
    if (element) {
      element.classList.add('hidden');
    }
  }

  async showDeviceId() {
    let { deviceId } = await chrome.storage.local.get('deviceId');
    console.log('[设备ID] 读取到的 deviceId:', deviceId);
    if (!deviceId) {
      // 兜底生成
      deviceId = `chrome_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      await chrome.storage.local.set({ deviceId });
      console.log('[设备ID] 兜底生成新 deviceId:', deviceId);
    }
    
    // 更新设备ID显示
    this.deviceId = deviceId;
    this.deviceIdElement.textContent = deviceId ? `设备ID: ${deviceId}` : '设备ID: 未生成';
    
    console.log('[设备ID] 最终显示:', this.deviceIdElement.textContent);
    
    // 显示设备信息摘要
    console.log('设备信息:', {
      deviceId: this.deviceId,
      isConnected: this.isConnected,
      userId: this.userId,
      userName: this.userName
    });
  }

  async handleLogin() {
    const userName = this.userNameInput.value.trim();
    const password = this.passwordInput.value.trim();

    if (!userName || !password) {
      this.showLoginError('请输入用户名和密码');
      return;
    }

    try {
      this.loginBtn.disabled = true;
      this.loginBtn.textContent = '登录中...';
      this.loginError.textContent = '';

      // 发送登录请求到background.js
      const response = await chrome.runtime.sendMessage({
        action: 'login',
        credentials: { userName, password }
      });

      if (response.success) {
        console.log('登录成功，用户信息:', response);
        this.showLoginSuccess('登录成功');
        
        // 从background script获取最新的用户信息
        const status = await chrome.runtime.sendMessage({ action: 'getStatus' });
        if (status) {
          this.userId = status.userId;
          this.token = status.token;
          this.userName = status.userName;
        }
        
        // 保存用户信息到本地存储
        await chrome.storage.local.set({
          userId: this.userId,
          token: this.token,
          userName: this.userName
        });

        console.log('准备切换界面，当前状态:', {
          userId: this.userId,
          token: this.token,
          userName: this.userName,
          loginSection: !!this.loginSection,
          registerSection: !!this.registerSection,
          mainContent: !!this.mainContent
        });
        this.hideElement(this.loginSection);
        this.hideElement(this.registerSection);
        this.showElement(this.mainContent);
        console.log('界面切换完成');
        await this.updateUI();
        await this.showDeviceId();
        
        // 确保用户信息显示
        this.updateUserInfo();
        
        // 等待设备注册完成（如果background script正在注册）
        setTimeout(async () => {
          try {
            const status = await chrome.runtime.sendMessage({ action: 'getStatus' });
            if (status && status.deviceId) {
              this.deviceId = status.deviceId;
              await this.showDeviceId();
            }
          } catch (e) {
            console.warn('获取设备状态失败:', e);
          }
        }, 2000); // 等待2秒让设备注册完成
        
        // 登录成功后主动获取连接状态
        try {
          const status = await chrome.runtime.sendMessage({ action: 'getStatus' });
          if (status && typeof status.isConnected === 'boolean') {
            this.isConnected = status.isConnected;
            this.updateConnectionStatus();
          }
        } catch (e) {
          console.warn('获取连接状态失败:', e);
        }
      } else {
        this.showLoginError(response.error || '登录失败，请检查用户名和密码');
      }
    } catch (error) {
      console.error('登录请求失败:', error);
      this.showLoginError('登录时发生错误，请重试');
    } finally {
      this.loginBtn.disabled = false;
      this.loginBtn.textContent = '登录';
    }
  }

  showLoginError(message) {
    this.loginError.textContent = message;
    this.loginError.className = 'login-error error';
  }

  showLoginSuccess(message) {
    this.loginError.textContent = message;
    this.loginError.className = 'login-error success';
  }

  async handleRegister() {
    const userName = this.regUserNameInput.value.trim();
    const password = this.regPasswordInput.value.trim();
    const confirmPassword = this.regConfirmPasswordInput.value.trim();

    if (!userName || !password || !confirmPassword) {
      this.showRegisterError('请填写所有字段');
      return;
    }

    if (password !== confirmPassword) {
      this.showRegisterError('两次输入的密码不一致');
      return;
    }

    if (password.length < 6) {
      this.showRegisterError('密码长度至少6位');
      return;
    }

    try {
      this.registerBtn.disabled = true;
      this.registerBtn.textContent = '注册中...';
      this.registerError.textContent = '';

      // 发送注册请求到background.js
      const response = await chrome.runtime.sendMessage({
        action: 'register',
        credentials: { userName, password }
      });

      if (response.success) {
        this.showRegisterSuccess('注册成功！正在自动登录...');
        // 注册成功后自动登录
        setTimeout(async () => {
          // 使用注册时的用户名和密码进行登录
          this.userNameInput.value = userName;
          this.passwordInput.value = password;
          await this.handleLogin();
        }, 1500);
        await this.showDeviceId();
      } else {
        this.showRegisterError(response.error || '注册失败，请重试');
      }
    } catch (error) {
      console.error('注册请求失败:', error);
      this.showRegisterError('注册时发生错误，请重试');
    } finally {
      this.registerBtn.disabled = false;
      this.registerBtn.textContent = '注册';
    }
  }

  showRegisterError(message) {
    this.registerError.textContent = message;
    this.registerError.className = 'login-error error';
  }

  showRegisterSuccess(message) {
    this.registerError.textContent = message;
    this.registerError.className = 'login-error success';
  }

  showRegisterForm() {
    this.hideElement(this.loginSection);
    this.showElement(this.registerSection);
    this.hideElement(this.mainContent);
    // 清空错误信息
    this.loginError.textContent = '';
    this.registerError.textContent = '';
  }

  showLoginForm() {
    this.hideElement(this.registerSection);
    this.showElement(this.loginSection);
    this.hideElement(this.mainContent);
    // 清空错误信息
    this.loginError.textContent = '';
    this.registerError.textContent = '';
  }
  
  setupEventListeners() {
    // 设置按钮点击事件
    this.settingsBtn.addEventListener('click', () => {
      chrome.runtime.openOptionsPage();
    });
    
    // 登录按钮点击事件
    this.loginBtn.addEventListener('click', () => this.handleLogin());

    // 注册按钮点击事件
    this.registerBtn.addEventListener('click', () => this.handleRegister());

    // 切换注册视图按钮
    this.showRegisterBtn.addEventListener('click', () => this.showRegisterForm());

    // 切换登录视图按钮
    this.showLoginBtn.addEventListener('click', () => this.showLoginForm());

    // 帮助按钮点击事件
    this.helpBtn.addEventListener('click', () => {
      this.showHelp();
    });

    // 登出按钮点击事件
    this.logoutBtn.addEventListener('click', () => {
      this.handleLogout();
    });

    // 验证Token按钮点击事件
    this.validateTokenBtn.addEventListener('click', () => {
      this.handleValidateToken();
    });
    
    // 监听来自background script的消息
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      this.handleMessage(request, sender, sendResponse);
    });
  }
  
  async loadStatus() {
    try {
      console.log('开始加载状态');
      
      // 加载统一配置
      if (typeof smartInputConfig !== 'undefined') {
        await smartInputConfig.loadFromStorage();
      } else {
        console.warn('smartInputConfig未定义，跳过配置加载');
      }
      
      // 添加重试机制，确保background script完全初始化
      let response = null;
      let retryCount = 0;
      const maxRetries = 3;
      
      while (retryCount < maxRetries) {
        try {
          response = await chrome.runtime.sendMessage({ action: 'getStatus' });
          if (response && response.deviceId) {
            console.log(`Background script状态获取成功 (尝试 ${retryCount + 1}/${maxRetries})`);
            break;
          }
        } catch (error) {
          console.log(`Background script状态获取失败 (尝试 ${retryCount + 1}/${maxRetries}):`, error.message);
        }
        
        retryCount++;
        if (retryCount < maxRetries) {
          console.log(`等待background script初始化，${retryCount * 500}ms后重试...`);
          await new Promise(resolve => setTimeout(resolve, retryCount * 500));
        }
      }
      
      if (response) {
        console.log('状态加载成功:', response);
        this.deviceId = response.deviceId;
        this.userId = response.userId;
        this.userName = response.userName;
        this.token = response.token; // 使用实际的token值
        this.isConnected = response.isConnected || false;
      } else {
        console.log('状态加载失败，使用默认值');
        this.deviceId = null;
        this.userId = null;
        this.userName = null;
        this.token = null;
        this.isConnected = false;
      }
      
      console.log('状态加载完成:', {
        deviceId: this.deviceId,
        userId: this.userId,
        userName: this.userName,
        hasToken: !!this.token,
        isConnected: this.isConnected
      });
      
      // 如果有登录信息，只在必要时验证token有效性
      if (this.userId && this.token) {
        console.log('检测到登录信息，保持登录状态');
        // 不进行网络验证，避免频繁验证导致的问题
        // token验证将在实际使用时进行（如WebSocket连接时）
      }
      
      // 立即更新所有状态显示
      this.updateConnectionStatus();
      await this.showDeviceId();
      this.updateUserInfo();
      
    } catch (error) {
      console.error('加载状态失败:', error);
      this.deviceId = null;
      this.userId = null;
      this.userName = null;
      this.token = null;
      this.isConnected = false;
      
      // 即使出错也要更新显示
      this.updateConnectionStatus();
      await this.showDeviceId();
      this.updateUserInfo();
    }
  }
  
  async updateUI() {
    console.log('更新UI，当前状态:', {
      isConnected: this.isConnected,
      userId: this.userId,
      userName: this.userName,
      deviceId: this.deviceId
    });
    
    // 检查登录状态并更新界面
    await this.checkLoginStatus();
    
    // 更新连接状态
    this.updateConnectionStatus();
    
    // 更新设备ID显示
    await this.showDeviceId();
    
    // 更新用户信息显示
    this.updateUserInfo();
    
    // 更新活动列表
    this.updateActivityList();
  }
  
  updateUserInfo() {
    if (this.userName) {
      this.userNameElement.textContent = this.userName;
      this.showElement(this.userInfo);
      // 更新状态区域中的用户信息
      if (this.userStatus) {
        this.userStatus.textContent = this.userName;
      }
      console.log('显示用户信息:', this.userName);
    } else {
      this.hideElement(this.userInfo);
      // 更新状态区域中的用户信息
      if (this.userStatus) {
        this.userStatus.textContent = '未登录';
      }
      console.log('隐藏用户信息');
    }
  }
  
  async checkLoginStatus() {
    try {
      // 使用当前实例的状态，这些状态已经在loadStatus中从background script同步
      console.log('检查登录状态:', {
        userId: this.userId,
        hasToken: !!this.token,
        userName: this.userName
      });

      if (this.userId && this.token && this.token.length > 10) {
        // 检查token是否看起来有效（不是空字符串或无效值）
        console.log('检测到有效的登录信息，保持登录状态');
        
        // 已登录，隐藏登录和注册界面
        this.hideElement(this.loginSection);
        this.hideElement(this.registerSection);
        this.showElement(this.mainContent);
        
        // 显示用户信息
        this.updateUserInfo();
        
        console.log('用户已登录，显示主界面');
      } else {
        // 未登录或token无效，显示登录界面
        console.log('未登录或token无效，显示登录界面');
        this.showElement(this.loginSection);
        this.hideElement(this.registerSection);
        this.hideElement(this.mainContent);
        
        // 隐藏用户信息
        this.hideElement(this.userInfo);
        
        // 清理无效的登录信息
        if (this.userId || this.token || this.userName) {
          console.log('清理无效的登录信息');
          this.userId = null;
          this.token = null;
          this.userName = null;
          // 通知background清理状态
          chrome.runtime.sendMessage({ action: 'logout' }).catch(console.error);
        }
        
        console.log('用户未登录，显示登录界面');
      }
    } catch (error) {
      console.error('检查登录状态失败:', error);
    }
  }

  async handleLogout() {
    try {
      console.log('开始登出流程');
      
      // 调用background script的登出方法
      await chrome.runtime.sendMessage({ action: 'logout' });
      
      // 清除本地存储的登录信息
      await chrome.storage.local.remove(['userId', 'token', 'userName']);
      
      // 重置本地状态
      this.userId = null;
      this.token = null;
      this.userName = null;
      
      // 切换界面显示
      this.showElement(this.loginSection);
      this.hideElement(this.registerSection);
      this.hideElement(this.mainContent);
      
      // 清空登录表单
      this.userNameInput.value = '';
      this.passwordInput.value = '';
      this.loginError.textContent = '';
      
      // 更新UI
      await this.updateUI();
      await this.showDeviceId();
      
      console.log('登出完成');
    } catch (error) {
      console.error('登出失败:', error);
    }
  }

  async handleValidateToken() {
    try {
      console.log('手动验证token...');
      
      const response = await chrome.runtime.sendMessage({ action: 'validateToken' });
      if (response && response.valid) {
        console.log('Token验证成功');
        this.showSuccess('Token验证成功');
      } else {
        console.log('Token验证失败');
        this.showError('Token验证失败，请重新登录');
        // 清除登录状态
        await this.handleLogout();
      }
    } catch (error) {
      console.error('Token验证失败:', error);
      this.showError('Token验证失败，可能是网络问题');
    }
  }
  
  updateConnectionStatus() {
    console.log('更新连接状态:', this.isConnected);
    const timestamp = new Date().toLocaleTimeString();
    
    if (this.isConnected) {
      this.statusDot.className = 'status-dot connected';
      this.statusText.textContent = `已连接 (${timestamp})`;
      if (this.connectionStatus) {
        this.connectionStatus.textContent = `已连接 - ${timestamp}`;
      }
      console.log('连接状态: 已连接');
      
      // 添加连接成功的活动记录
      this.addActivity('🔗', `WebSocket连接成功 - ${timestamp}`);
    } else {
      this.statusDot.className = 'status-dot disconnected';
      this.statusText.textContent = `未连接 (${timestamp})`;
      if (this.connectionStatus) {
        this.connectionStatus.textContent = `未连接 - ${timestamp}`;
      }
      console.log('连接状态: 未连接');
      
      // 添加连接失败的活动记录
      this.addActivity('❌', `WebSocket连接断开 - ${timestamp}`);
    }
    
    // 更新活动列表
    this.updateActivityList();
  }
  
  updateRecordingStatus() {
    // 移除录音状态更新功能
    return;
  }
  
  async updateDeviceInfo() {
    await this.showDeviceId();
  }
  
  updateActivityList() {
    // 这里可以从存储中加载最近的活动记录
    const activities = this.getRecentActivities();
    
    if (activities.length === 0) {
      this.activityList.innerHTML = `
        <div class="activity-item">
          <span class="activity-icon">📝</span>
          <span class="activity-text">暂无活动</span>
        </div>
      `;
    } else {
      this.activityList.innerHTML = activities.map(activity => `
        <div class="activity-item">
          <span class="activity-icon">${activity.icon}</span>
          <span class="activity-text">${activity.text}</span>
        </div>
      `).join('');
    }
  }
  
  getRecentActivities() {
    // 从存储中获取最近的活动记录
    // 这里暂时返回空数组，实际应该从chrome.storage中读取
    return [];
  }
  
  async toggleVoiceRecording() {
    // 移除录音功能
    return;
  }
  
  async syncCurrentText() {
    // 移除文字同步功能
    return;
  }
  
  showHelp() {
    // 打开帮助页面
    chrome.tabs.create({
      url: chrome.runtime.getURL('help.html')
    });
  }
  
  handleMessage(request, sender, sendResponse) {
    switch (request.action) {
      case 'syncCompleted':
        this.showSuccess('文字同步完成');
        break;
        
      case 'syncFailed':
        this.showError('文字同步失败');
        break;
        
      default:
        break;
    }
  }
  
  showError(message) {
    // 显示错误消息
    const notification = document.createElement('div');
    notification.className = 'error-notification';
    notification.textContent = message;
    notification.classList.add('notification', 'error-notification');
    document.body.appendChild(notification);
    setTimeout(() => {
      if (notification.parentNode) {
        notification.remove();
      }
    }, 3000);
  }

  showInfo(message) {
    // 显示信息消息
    const notification = document.createElement('div');
    notification.className = 'info-notification';
    notification.textContent = message;
    notification.classList.add('notification', 'info-notification');
    document.body.appendChild(notification);
    setTimeout(() => {
      if (notification.parentNode) {
        notification.remove();
      }
    }, 3000);
  }

  showSuccess(message) {
    // 显示成功消息
    const notification = document.createElement('div');
    notification.className = 'success-notification';
    notification.textContent = message;
    notification.classList.add('notification', 'success-notification');
    document.body.appendChild(notification);
    setTimeout(() => {
      if (notification.parentNode) {
        notification.remove();
      }
    }, 3000);
  }

  addActivity(icon, text) {
    // 添加活动记录
    const activity = { icon, text, timestamp: Date.now() };
    // 保存到存储
    this.saveActivity(activity);
    // 更新UI
    this.updateActivityList();
  }

  async saveActivity(activity) {
    try {
      const result = await chrome.storage.local.get(['activities']);
      const activities = result.activities || [];
      // 添加新活动到开头
      activities.unshift(activity);
      // 只保留最近10个活动
      if (activities.length > 10) {
        activities.splice(10);
      }
      await chrome.storage.local.set({ activities });
    } catch (error) {
      console.error('保存活动记录失败:', error);
    }
  }

  async getActivities() {
    try {
      const result = await chrome.storage.local.get(['activities']);
      return result.activities || [];
    } catch (error) {
      console.error('获取活动记录失败:', error);
      return [];
    }
  }

  async logout() {
    await chrome.storage.local.remove(['userId', 'token']);
    this.userId = null;
    this.token = null;
    this.showElement(this.loginSection);
    this.hideElement(this.registerSection);
    this.hideElement(this.mainContent);
    await this.updateUI();
    await this.showDeviceId();
  }
}

// 初始化弹出窗口

document.addEventListener('DOMContentLoaded', () => {
  window.smartInputPopup = new SmartInputPopup();
});

window.addEventListener('unload', () => {
  if (window.smartInputPopup && window.smartInputPopup.statusInterval) {
    clearInterval(window.smartInputPopup.statusInterval);
  }
});